package com.yd.mvc.pc.goodsController;

import com.yd.app.service.pc.goodsService.GoodsService;
import com.yd.app.service.pc.goodsWeightService.GoodsWeightService;
import com.yd.app.util.BusinessException;
import com.yd.app.util.ExcelUtil;
import com.yd.domain.business.*;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.GoodsSearchParam;
import com.yd.domain.sys.DicEnum;
import com.yd.domain.sys.User;
import com.yd.mvc.baseController.BaseController;
import com.yd.mvc.baseController.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zy
 * @create 2018-03-07 17:40
 * @desc
 **/
@RestController
@RequestMapping(value = "/api/goods")
public class GoodsController extends BaseController{
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsWeightService goodsWeightService;
    @Value("${base.img.url}")
    private String base_img_url;
    /**
     * @Author: zg
     * @Desc: 添加商品基础信息
     * @Date:  2018/3/8
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void addGoods(@RequestBody @Valid Goods goods)  {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        goods.setUpdateUser(user.getUserId());
        goods.setUpdateTime(new Date());
        String goodsId=goods.getId().toString();
        List<GoodsWeight> list=goods.getGoodsWeightList();
        for(GoodsWeight goodsWeight:list){
            goodsWeight.setGoodsId(goodsId);
            goodsWeightService.addGoodsWeight(goodsWeight);
        }
        goodsService.addGoods(goods);
    }

    /**
     * 删除商品
     * @param goodsId
     */
    @RequestMapping(value = "/delete/{goodsId}", method = RequestMethod.DELETE)
    public void deleteGoods(@PathVariable("goodsId")String goodsId) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        goodsService.deleteGoodsById(goodsId);
    }

    /**
     * 修改商品
     * @param goods
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public void updateGoods(@RequestBody Goods goods) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        goods.setUpdateUser(user.getUserId());
        goods.setUpdateTime(new Date());
        String goodsId=goods.getId().toString();
        goodsWeightService.deleteGoodsWeightByGoodsId(goodsId);
        List<GoodsWeight> list=goods.getGoodsWeightList();
        for(GoodsWeight goodsWeight:list){
            goodsWeight.setGoodsId(goodsId);
            goodsWeightService.addGoodsWeight(goodsWeight);
        }
        goodsService.updateGoods(goods);
    }

    /**
     * 上/下架商品
     * @param goodsId
     * @param status
     */
    @RequestMapping(value = "/updateStatus/{goodsId}/{status}", method = RequestMethod.GET)
    public void updateStatus(@PathVariable("goodsId")String goodsId,@PathVariable("status")String status) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        goodsService.updateGoodsStatus(goodsId,status);
    }

    /**
     * 审核商品
     * @param goodsId
     * @param checkStatus
     */
    @RequestMapping(value = "/checkStatus/{goodsId}/{checkStatus}", method = RequestMethod.GET)
    public void checkStatus(@PathVariable("goodsId")String goodsId,@PathVariable("checkStatus")String checkStatus) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        goodsService.updateGoodsCheckStatus(goodsId,user.getUserId(),new Date(),checkStatus);
    }

    /**
     * 查询商品
     * @param goodsId
     */
    @RequestMapping(value = "/getGoodsById/{goodsId}", method = RequestMethod.GET)
    public Goods getGoodsById(@PathVariable("goodsId")String goodsId)  {
        Goods goods=goodsService.getGoodsById(goodsId);
        return goods;
    }

    /**
     * 商品信息列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/getList/{pageIndex}/{pageSize}", method = RequestMethod.POST)
    public PageModel goodsList(@RequestBody GoodsSearchParam param, @PathVariable("pageIndex")int pageIndex, @PathVariable("pageSize")int pageSize)throws Exception {
        PageModel pm=goodsService.goodsList(param,pageIndex,pageSize);
        return pm;
    }

    /**
     * 删除产品图片
     * @param url
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/deleteImage/{goodsId}/{imageId}", method = RequestMethod.GET)
    public String  deleteGoodsImage(@RequestParam String url,@PathVariable("goodsId")String goodsId,@PathVariable("imageId")String imageId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        url=new String(url.getBytes("iso8859-1"),"utf-8");
        request.setCharacterEncoding("utf-8");
        if(!StringUtils.isEmpty(url)){
            goodsService.deleteGoodsImage(goodsId,imageId,url);
        }else{
            goodsService.deleteGoodsImage(goodsId,imageId);
        }
        return "true";
    }

    /**
     * 查询商品图片信息
     * @param goodsId
     */
    @RequestMapping(value = "/getGoodsPic/{goodsId}", method = RequestMethod.GET)
    public List<Pic> getAllPic(@PathVariable("goodsId")String goodsId)  {
        List<Pic> list=goodsService.getAllPic(goodsId);
        return list;
    }

    /**
     * 商品图片
     * @param param
     */
    @RequestMapping(value = "/updateIconUrl", method = RequestMethod.POST)
    public void updateIconUrl(@RequestBody GoodsIcon param) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        String goodsId=param.getGoodsId().toString();
        String pic_path=param.getPic_path().toString();
        goodsService.updateIconUrl(goodsId,pic_path);
    }

    /**
     * 删除商品展示图片
     * @param id
     */
    @RequestMapping(value = "/updateIconUrl/{id}", method = RequestMethod.GET)
    public void updateIconUrl(@PathVariable("id")String id) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        goodsService.updateIconUrl(id);
    }

    /**
     * 添加商品轮播图片
     * @param param
     */
    @RequestMapping(value = "/addGoodsPic", method = RequestMethod.POST)
    public void addGoodsPic(@RequestBody GoodsIcon param) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        Pic pic=new Pic();
        String goodsId=param.getGoodsId().toString();
        String pic_path=param.getPic_path().toString();
        GoodsPic goodsPic=new GoodsPic();
        goodsPic.setGoodsId(goodsId);
        goodsPic.setPicId(pic.getId().toString());
        pic.setPicUrl(pic_path);
        goodsService.addGoodsPic(goodsPic);
        goodsService.addPic(pic);
    }

    @RequestMapping(value = "/copyGoodsByIds", method = RequestMethod.POST)
    public void copyGoodsByIds(@RequestBody String[]ids)  {
        for(String id:ids){
            Goods goods=goodsService.getGoodsById(id);
            goods.setId(new Goods().getId());
            List<GoodsWeight> goodsWeightList=new ArrayList<>();
            goodsWeightList=goodsWeightService.getGoodsWeight(id);//获取原规格
            for(GoodsWeight goodsWeight:goodsWeightList){
                goodsWeight.setId(new GoodsWeight().getId());
                goodsWeight.setGoodsId(goods.getId());
                goodsWeightService.addGoodsWeight(goodsWeight);
            }
            List<Pic> list=goodsService.getAllPic(id);//获取原图片
            for(Pic pic:list){
                //复制图片
                String oldPath=base_img_url+pic.getPicUrl();
                String newPath=base_img_url;
                String[] strs=pic.getPicUrl().split("_");
                String fileName=new Date().getTime()+"_"+strs[strs.length-1];
                ExcelUtil.createNewFile(oldPath,newPath,fileName);
                pic.setPicUrl(fileName);
                pic.setId(new Pic().getId());
                GoodsPic goodsPic=new GoodsPic();
                goodsPic.setGoodsId(goods.getId());
                goodsPic.setPicId(pic.getId());
                pic.setPicUrl(pic.getPicUrl());
                goodsService.addPic(pic);
                goodsService.addGoodsPic(goodsPic);
            }
            String[] strs=goods.getIconUrl().split("_");
            String fileName=new Date().getTime()+"_"+strs[strs.length-1];
            ExcelUtil.createNewFile(base_img_url+goods.getIconUrl(),base_img_url,fileName);
            goods.setCheckStatus(DicEnum.CHECK.UN_CHECK);
            goods.setIconUrl(fileName);
            goods.setTitle(goods.getTitle()+"_copy");
            goodsService.addGoods(goods);
        }

    }

    //批量上架
    @RequestMapping(value = "/groundingByIds", method = RequestMethod.POST)
    public void groundingByIds(@RequestBody String[]ids)  {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        String status="1";
        for(String id:ids){
            goodsService.updateGoodsStatus(id,status);
        }
    }

    //批量下架
    @RequestMapping(value = "/undercarriageByIds", method = RequestMethod.POST)
    public void undercarriageByIds(@RequestBody String[]ids)  {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        String status="0";
        for(String id:ids){
            goodsService.updateGoodsStatus(id,status);
        }
    }

    //批量审核
    @RequestMapping(value = "/reviewByIds", method = RequestMethod.POST)
    public void reviewByIds(@RequestBody String[]ids)  {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.GOODS_MANAGER);//验证权限
        }
        String checkStatus="1";
        for(String id:ids){
            goodsService.updateGoodsCheckStatus(id,user.getUserId(),new Date(),checkStatus);
        }
    }
}
